package tail

import (
	"fmt"
	"logAgent/etcd"
	"logAgent/utils"
	"time"
)

//TailManager 监控任务管理
type TailManager struct {
	taskMap     map[string]*TailTask  //监控任务map
	logEntries  []*etcd.LogEntry      //日志配置信息
	newConfChan chan []*etcd.LogEntry //etcd日志配置信息管道
}

//NewTailManager 新建监控任务管理类
func NewTailManager(logEntries []*etcd.LogEntry) *TailManager {
	tail_manager := TailManager{
		taskMap:     make(map[string]*TailTask, 8),
		logEntries:  logEntries,
		newConfChan: make(chan []*etcd.LogEntry), //无缓冲channel
	}

	for _, v := range logEntries {
		tailTask := newTailTask(v.Path, v.Topic)
		if tailTask != nil {
			key := fmt.Sprintf("%s_%s", v.Path, v.Topic) //格式化键，用作判断
			tail_manager.taskMap[key] = tailTask
		}
	}

	go tail_manager.run()

	return &tail_manager
}

//GetNewConfChan 获取配置信息管道
func (t *TailManager) GetNewConfChan() chan []*etcd.LogEntry {
	return t.newConfChan
}

//run 执行获取新配置信息操作
func (t *TailManager) run() {
	for {
		select {
		case newConf := <-t.newConfChan: //获取etcd键下的信息，是否被修改过
			//添加新的配置信息
			for _, v := range newConf {
				key := fmt.Sprintf("%s_%s", v.Path, v.Topic)
				//验证当前的日志配置信息是否已经启用任务了
				if _, ok := t.taskMap[key]; ok {
					continue
				}
				tailTask := newTailTask(v.Path, v.Topic)
				if tailTask != nil {
					t.taskMap[key] = tailTask
				}
				//添加新的监控
				utils.Log.Infof("Path: %s, Topic: %s 的任务新增成功\n", v.Path, v.Topic)
			}
			//删除不存在的配置信息对应的任务
			for _, i := range t.logEntries {
				flag := true
				for _, j := range newConf {
					if j.Path == i.Path && j.Topic == i.Topic {
						flag = false
						break
					}
				}
				if flag {
					key := fmt.Sprintf("%s_%s", i.Path, i.Topic)
					t.taskMap[key].cancel()
				}
				utils.Log.Infof("Key: %s 不存在了, 对应任务已经被删除了")
			}
			//重置
			t.logEntries = newConf
		default:
			time.Sleep(time.Second)
		}
	}
}
